package de.joergviola.mobj.client.storage;

import java.util.Date;
import java.util.List;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;

import de.joergviola.mobj.shared.EntityWriter;
import de.joergviola.mobj.shared.Persistable;
import de.joergviola.mobj.shared.UnknownEntityException;

public class JSONEntityWriter implements EntityWriter {

	private final JSONObject json;
	private final StorageTransaction tx;

	public JSONEntityWriter(StorageTransaction tx, JSONObject json) {
		this.tx = tx;
		this.json = json;
	}

	@Override
	public void writeString(String name, String value) {
		if (value == null)
			json.put(name, null);
		else
			json.put(name, new JSONString(value));
	}

	@Override
	public void writeLong(String name, Long value) {
		if (value == null)
			json.put(name, null);
		else
			json.put(name, new JSONNumber(value));
	}

	@Override
	public void writeDouble(String name, Double value) {
		if (value == null)
			json.put(name, null);
		else
			json.put(name, new JSONNumber(value));
	}

	@Override
	public void writeDate(String name, Date value) {
		if (value == null)
			json.put(name, null);
		else
			json.put(name, new JSONNumber(value.getTime()));
	}

	@Override
	public void writeListLong(String name, List<Long> value) {
		if (value == null) {
			json.put(name, null);
			return;
		}
		JSONArray array = new JSONArray();
		int index = 0;
		for (Long l : value) {
			array.set(index++, new JSONNumber(l));
		}
		json.put(name, array);
	}

	@Override
	public void writeListString(String name, List<String> value) {
		if (value == null) {
			json.put(name, null);
			return;
		}
		JSONArray array = new JSONArray();
		int index = 0;
		for (String s : value) {
			array.set(index++, new JSONString(s));
		}
		json.put(name, array);
	}

	@Override
	public void writeStringArray(String name, String[] value) {
		if (value == null) {
			json.put(name, null);
			return;
		}

		JSONArray array = new JSONArray();
		for (int i = 0; i < value.length; i++) {
			array.set(i, new JSONString(value[i]));
		}
		json.put(name, array);
	}

	@Override
	public void writePersistable(String name, Persistable value)
			throws UnknownEntityException {
		if (value == null)
			json.put(name, null);
		else {
			Long id = (Long) tx.insertOrUpdate(value);
			json.put(name, new JSONNumber(id));
		}
	}
}